<?php

require_once 'Basic.php';

class ModelTypeCreate extends BasicEntity {
  
  private static $actionName = "Create";
  
  private static $nameField = "name";
  
  public function __construct() {
    $this->fields = array(
        new FormField(true, ModelTypeCreate::$nameField, "Nome", new FormFieldTextLine())
    );
    $this->processFields();
  }
  
  public function actionDescription() {
    return ModelTypeCreate::$actionName;
  }
  
  public function actionCreate($userInput) {
		$name = $userInput[ModelTypeCreate::$nameField];
  
		$db = new DBUtils();
		 
		try {
     $db->connect();
     
     $db->runQuery("select idTipoModelo from TipoModelo where nome = ?", array($name));
     if($db->getItem() !== null) {
       $this->fields[ModelTypeCreate::$nameField]->setValid(false);
       return "Tipo com nome ${name} j&aacute; cadastrado.";
     }
     
     $db->runQuery("insert into TipoModelo (nome) values(?)", array($name));
     
     $db->close(true);
    }
    catch(DBError $e) {
     $db->close(false);
     logMessage($e->errors, "ModelTypeCreate");
     return "Falha no banco de dados. O erro foi reportado.";
    }
    
    return true;
  }


}

mustBeEmployee();
correctStdFormGET();
$page = new Page("Cadastro de Tipos de Ve&iacute;culo");
$modelTypeCreate = new ModelTypeCreate();
$form = new StdForm($modelTypeCreate, $_GET, $_POST,
        "<p>" . htmlentities("Campos em negrito são obrigatórios.") . "</p>",
        "<p>" . htmlentities("Cadastro realizado com sucesso.") . "</p>",
        "ModelTypeCreate.php");
$form->processForm();
$page->addContent($form->getHtml());
echo $page->getHtml();